/*
 * Store.cpp
 *
 *  Created on: 29.10.2013
 *      Author: ulgish
 */

#include <lab2/Store.h>

#include <sstream>

using std::stringstream;

namespace DT {


    bool Store::operator ++(int int1)
    {
    	pthread_mutex_lock(&mutex);
    	DT::writer << std::string("Supplier:: ") + toString();
    	if (curr < maxCount){
    		curr++;
    		pthread_mutex_unlock(&mutex);
    		return true;
    	}else{
    		pthread_mutex_unlock(&mutex);
    		return false;
    	}

    }

    bool Store::operator --(int int1)
    {
    	pthread_mutex_lock(&mutex);
    	DT::writer << std::string("Consumer:: ") + toString();
    	if (curr > 0){
    		curr--;
    		pthread_mutex_unlock(&mutex);
    		return true;
    	}else{
    		pthread_mutex_unlock(&mutex);
    		return false;
    	}
    }

Store::Store(int maxCount)
    {
		stringstream ss;
		this->maxCount = maxCount;
		ss << "Object of class Store created:\n";
		ss << "maxCount:\t" << maxCount << "\n";
		ss <<"Mutex init\n";
		pthread_mutex_init(&mutex, NULL);
		DT::writer << ss.str();
		DT::writer.flush();
    }

    std::string DT::Store::toString()
    {
    	stringstream ss;
    	ss << "Store:\n";
    	ss << "current size:\t" << curr << "\n";
    	ss << "Max size:\t" << maxCount << "\n";
    	return std::string(ss.str());
    }

    Store::~Store() {
	// TODO Auto-generated destructor stub
    	pthread_mutex_destroy(&mutex);
}

}
